package com.application.Activity;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.RemoteViews;
import android.widget.TextView;

import com.application.Custom.ThirdPartyAppDialog;
import com.application.Network.Protocol;
import com.application.Tree.MyHandlerInterface;
import com.application.outdoor.pojo.FileSharePOJO;

public class od_fileInfoActivity extends Activity {
	private static int SHARE_FILE_CODE = 1;
	public static FileSharePOJO file;
	private Button btnOpen, btnClose;
	public static boolean open = true;
	private TextView txtTenFile, txtNguoiUp, txtNgayUp, txtGhiChu;
	Notification notifDownload;
	NotificationManager notificationManager;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.od_activity_file_info);		
		txtTenFile = (TextView) findViewById(R.id.txtTenFile);
		txtNguoiUp = (TextView) findViewById(R.id.txtNguoiUp);
		txtNgayUp = (TextView) findViewById(R.id.txtNgayUp);
		txtGhiChu = (TextView) findViewById(R.id.txtGhiChu);
		txtTenFile.setText(file.getTenFile());
		txtNguoiUp.setText(file.getNguoiUp());
		txtNgayUp.setText(new SimpleDateFormat("dd-MM-yyyy hh:mm:ss").format(new Date(file.getThoiGian())));
		txtGhiChu.setText(file.getGhiChu());
		btnOpen = (Button) findViewById(R.id.btnOpen);
		btnClose = (Button) findViewById(R.id.btnClose);
		if (!open) {
			btnOpen.setText("Tải về");
		}
		btnClose.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish(); // CZX
			}
		});

		btnOpen.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (open) {
					openFile();
				} else {
					Intent fileOpen = new Intent(od_fileInfoActivity.this, FrmSelectFile.class);
					fileOpen.putExtra(FrmSelectFile.FILE_NAME, file.getTenFile());
					startActivityForResult(fileOpen, SHARE_FILE_CODE);
					// finish();
				}

			}
		});
	}

	@Override
	public synchronized void onActivityResult(final int requestCode, int resultCode, final Intent data) {
		if (requestCode == SHARE_FILE_CODE && resultCode == RESULT_OK) {
			String selectFilePath = data.getStringExtra(FrmSelectFile.RESULT_PATH);
			// FileSharePOJO f=lstFile.get(postion);
			// od_fileInfoActivity.file=new FileSharePOJO();
			// od_fileInfoActivity.file.setId(f.getId());
			// od_fileInfoActivity.file.setIdNhom(f.getIdNhom());
			// od_fileInfoActivity.file.setNguoiUp(f.getNguoiUp());
			 od_fileInfoActivity.file.setPath(selectFilePath);
			// od_fileInfoActivity.file.setTenFile(f.getTenFile());
			// od_fileInfoActivity.file.setThoiGian(f.getThoiGian());
			
			new DownloadFileTask().execute(file.getId() + "", selectFilePath);
			finish();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.od_activity_file_info, menu);
		return true;
	}

	private void openFile() {
		PackageManager packageManager = getPackageManager();
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.addCategory(Intent.CATEGORY_DEFAULT);
		MimeTypeMap m = MimeTypeMap.getSingleton();
		String mineType = m.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(file.getPath()));
		
		Log.d(Protocol.TAG,"mimeType= "+mineType);
		intent.setType(mineType);
		final List<ResolveInfo> data = packageManager.queryIntentActivities(intent, 0);
		if (data == null || data.size() == 0) {
			MESApplication.showDialog(od_fileInfoActivity.this, "Lỗi", "Không tìm thấy chương trình mở tập tin này!");
		} else {
			ThirdPartyAppDialog dialog = new ThirdPartyAppDialog(od_fileInfoActivity.this, "Chọn chương trình", data);
			dialog.setItemClick(new MyHandlerInterface() {

				@Override
				public void onHandle(Object obj) {
					Integer index = (Integer) obj;
					ResolveInfo info = data.get(index);
					Intent iOpenFile = new Intent(Intent.ACTION_MAIN);
					iOpenFile.addCategory(Intent.CATEGORY_LAUNCHER);
					iOpenFile.setComponent(new ComponentName(info.activityInfo.packageName, info.activityInfo.name));
					iOpenFile.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

					Uri uriData = Uri.parse(file.getPath());
					iOpenFile.setData(uriData);
					startActivity(iOpenFile);
				}
			});
			dialog.show();
		}

	}

	private class DownloadFileTask extends AsyncTask<String, Integer, String> {

		@Override
		protected String doInBackground(String... params) {
			try {

				notifDownload.contentView.setTextViewText(R.id.status_text, "Đang tải về: " + params[1]);
				URL url = new URL(od_ShareFileActivity.DOWNLOAD_URL + "?" + Protocol.ID + "=" + params[0]);
				URLConnection connection = url.openConnection();
				connection.connect();

				InputStream input = new BufferedInputStream(url.openStream());
				OutputStream output = new FileOutputStream(params[1]);

				int fileLength = connection.getContentLength();

				byte data[] = new byte[1024];
				long total = 0;
				int count;
				long currentTime = 0;
				long cDownTime = 0;
				while ((count = input.read(data)) != -1) {
					total += count;
					currentTime = System.currentTimeMillis();
					if (currentTime - cDownTime > 500) {
						publishProgress((int) (total * 100 / fileLength));
						cDownTime = currentTime;
					}
					output.write(data, 0, count);
				}

				output.flush();
				output.close();
				input.close();
			} catch (Exception e) {
				Log.d(Protocol.TAG, "Download file bi loi:" + e.getMessage());

			}
			try {
				Thread.sleep(2000);
			} catch (Exception e) {
				// TODO: handle exception
			}
			return params[1];

		}

		@Override
		protected void onProgressUpdate(Integer... progress) {
			notifDownload.contentView.setProgressBar(R.id.status_progress, 100, progress[0], false);
			notificationManager.notify(od_ShareFileActivity.DOWNLOAD_NOF_ID, notifDownload);

		}

		@Override
		protected void onPostExecute(String ui) {
			od_fileInfoActivity.open=true;
			notificationManager.cancel(od_ShareFileActivity.DOWNLOAD_NOF_ID);
			GCMIntentService.notification(getBaseContext(), "Đã tải xong tập tin: " + ui, od_fileInfoActivity.class,
					null);
		}

		@Override
		protected void onPreExecute() {
			initDownload();
			notificationManager.notify(od_ShareFileActivity.DOWNLOAD_NOF_ID, notifDownload);
		}
	}

	private void initDownload() {

		// Intent intent=new Intent(getBaseContext(),od_fileInfoActivity.class);
		PendingIntent pendingIntent = PendingIntent.getActivity(getBaseContext(), 0, null, 0);
		notifDownload = new Notification(R.drawable.icon, "Tải tài liệu", System.currentTimeMillis());
		notifDownload.flags |= Notification.FLAG_ONGOING_EVENT;
		notifDownload.contentView = new RemoteViews(getApplicationContext().getPackageName(),
				R.layout.od_download_progress);
		notifDownload.contentIntent = pendingIntent;
		notifDownload.contentView.setImageViewResource(R.id.status_icon, R.drawable.ic_file_download);
		notifDownload.contentView.setProgressBar(R.id.status_progress, 100, 0, false);
		notificationManager = (NotificationManager) getApplicationContext().getSystemService(
				Context.NOTIFICATION_SERVICE);
	}
}
